import React from 'react';
import Item from './SbItem';
export default class FromDemo extends React.Component {
  constructor(props) {
    super(props)
    this.formData = {}
  }
  onChange (...args) {
    this.formData = {
      ...this.formData,
      [args[0]]: args[1]
    }
    // 将form的state传出去
    this.props.onChange && this.props.onChange(JSON.parse(JSON.stringify(this.formData)), ...args)
  }
  render () {
    const onChange = this.onChange.bind(this)
    const initialValues = this.props.formData || {}
    // 插入到最后
    const defaultChildren = this.props.children && this.props.children.filter((item) => {
      return item && !item.props.slot
    })

    // 插入到指定位置
    const slotChildren = this.props.children && this.props.children.filter((item) => {
      return item && item.props.slot
    })

    return (
      <div className="sb-form">
        {
          this.props.schema && Object.keys(this.props.schema).map((name) => {
            const item = this.props.schema[name]
            const itemProps = {
              name, // 对应formData 

              ...item.itemProps,
              key: name,
              onChange
            }

            // 默认值相关
            if (initialValues[name] !== undefined) {
              itemProps.initialValue = initialValues[name]
            }

            if (item.type === 'slot') {
              const el = slotChildren.find((el) => {
                return el.props.slot === name
              })
              if (el) {
                return React.cloneElement(el, {
                  key: name,
                  onChange
                })
              }
            } else {
              // TODO 每多一个组件就要加一个
              let fuck = null
              if (item.type === 'text') {
                fuck = React.createElement('input', item.fieldProps || {})
              } else if (item.type === 'select') {
                fuck = React.createElement('select', item.fieldProps || {}, item.options && item.options.map((o, k) => {
                  return React.createElement('option', {
                    value: o.value,
                    key: k
                  }, o.label)
                }))
              }
              return <Item {...itemProps}>
                {fuck}
              </Item>
            }

          })
        }
        {React.Children.map(defaultChildren, (v, k) => {
          // TODO 我想给他加个props 直接改不让改···
          return React.cloneElement(v, {
            key: k,
            onChange
          })
        })}
      </div>
    )
  }
}

